<template>
  <div class="app-container">
    <div style="padding-right: 100px">
      <el-form v-bind="formProps">
        <!-- v-if="(data.document_type == 2 || data.document_type == 3)" -->
        <el-form-item label="上传标签档案" v-if="(data.document_type == 2 || data.document_type == 3)">
          <span slot="label">
            <span class="text-red">*</span>
            <span>上传标签档案</span>
          </span>
          <el-upload :file-list="labelFiles" v-bind="labelUploaderProps">
            <el-button size="mini" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <div v-else>
          <el-form-item label="标签尺寸" v-if="data.size">
            <el-input class="mr-10" v-model="data.size" clearable style="width: 160px" disabled>
            </el-input>
          </el-form-item>
          <el-form-item label="标签设计">
            <el-button type="success" @click="labelDesign(laberDesignId)">标签设计</el-button>
          </el-form-item>
        </div>
        <el-form-item label="标签字段">
          <span slot="label">
            <span class="text-red">*</span>
            <span>标签字段</span>
          </span>
          <!-- v-if="data.detail && data.detail.length == 0" -->
          <el-button style="margin-left: 3px" v-show="!data.detail_list.length" type="primary" @click="addDetail()"
            size="mini" icon="el-icon-plus" circle>
          </el-button>
          <div>
            <el-row :gutter="15" v-for="(d, i) in data.detail_list" :key="i" style="margin: 0; margin-bottom: 10px">
              <el-col :span="6">
                <el-select v-model="d.name" placeholder="视图名称" style="width: 100%">
                  <el-option v-for="i in viewOptions" :key="i.id" :label="i.label" :value="i.value"> </el-option>
                </el-select>
              </el-col>
              <el-col :span="15">
                <el-select v-model="d.value" placeholder="不可为空值的字段" class="mb-5" style="width: 100%" multiple
                  filterable>
                  <el-option v-for="i in fieldOptions(d)" :key="i.id" :label="i.param_value + ' ' + i.param_condition1"
                    :value="i.param_value"></el-option>
                </el-select>
                <el-select v-model="d.allow_null_value" placeholder="可为空值的字段" style="width: 100%" multiple filterable>
                  <el-option v-for="i in fieldOptions(d)" :key="i.id" :label="i.param_value + ' ' + i.param_condition1"
                    :value="i.param_value"></el-option>
                </el-select>
              </el-col>
              <el-col :span="3">
                <el-button type="danger" size="mini" icon="el-icon-minus" @click="removeDetail(i)" circle>
                </el-button>
                <el-button style="margin-left: 3px" type="primary" @click="addDetail(i)" size="mini" icon="el-icon-plus"
                  circle></el-button>
                <!--  v-show="i == data.detail.length - 1" -->
              </el-col>
            </el-row>
          </div>
        </el-form-item>
      </el-form>
      <div class="text-right">
        <el-button type="primary" @click.native="submit(false)" :loading="submitLoading">
          确认
        </el-button>
        <el-button type="warning" v-if=" isCommon==0" @click.native="submit(true)" :loading="submitLoading">
          确认并下一步
        </el-button>
      </div>
      <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" class="design-dialog" title="标签设计"
        :visible.sync="designVisible" width="80%">
        <iframe :src="designUrl" width="100%" scrolling='auto' style="min-height: 550px"></iframe>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import commonMixin from '@/views/_common/mixin'
import { getToken } from '@/utils/auth'
import _ from 'lodash'
import { download } from '@/utils/index.js'
export default {
  mixins: [commonMixin],
  props: {
    laberDesignId: {
      typeof: String,
      default: '',
    },
    isCommon: {
      typeof: Number,
      default: 0,
    },
  },
  data() {
    return {
      api: this.$api.label,
      apiSingle: this.$api.label + 'getbyid',
      baseUrl: this.$api.baseUrl,
      apiCreate: this.$api.label + 'modify',
      apiEdit: this.$api.label + 'modify',
      formProps: {
        dialogWidth: '80%',
        labelWidth: '120px',
      },
      initData: { detail_list: [{ value: null, allow_null_value: null }], labels: [] },
      data: { detail_list: [{ value: null, allow_null_value: null }], labels: [] },
      labelFiles: [],
      viewOptions: [],
      formData: new FormData(),
      designBaseUrl: '/labelDesign/index.html',
      designUrl: null,
      designVisible: false,
      labelUploaderProps: {},
    }
  },
  created: function () {
    this.getTabInit()
  },
  watch: {
    laberDesignId: {
      handler(v, o) {
        if (!!v && v !== o) {
          this.getInfo()
          this.formData = new FormData()
        } else {
          this.formData = new FormData()
        }
      },
      immediate: true,
    },
  },
  methods: {
    submit(flag) {
      let url = this.api + 'ModifyLabelDesign'
      let views = this.data.detail_list.map((i) => i.name)
      //检查
      if (_.uniq(views).length != views.length) {
        this.$message({
          message: '标签字段数据中，视图名称不能重复',
          type: 'error',
        })
        return
      }
      if (!this.data.detail_list || this.data.detail_list.length <= 0) {
        this.$message({
          message: `标签字段必须维护。`,
          type: 'error',
        })
        return
      }
      let check = this.data.detail_list.filter((i) => {
        return _.intersection(i.value, i.allow_null_value).length > 0
      })
      if (check.length > 0) {
        this.$message({
          message: `标签字段数据中，同一字段不能同时出现在 允许为空 和 不可为空 中`,
          type: 'error',
        })
        return
      }
      check = this.data.detail_list.filter((i) => {
        return i.value.length == 0 && i.allow_null_value.length == 0
      })
      if (check.length > 0) {
        this.$message({
          message: `选择的视图 ${check[0].name} 字段不能为空`,
          type: 'error',
        })
        return
      }
      let data = this.formatBeforeSave(this.data)
      this.formData.append('model', JSON.stringify(data))
      this.submitLoading = true
      this.$request(url, this.formData, 'post')
        .then((r) => {
          this.submitLoading = false
          this.$message({
            message: '操作成功',
            type: 'success',
          })
          this.editFormVisible = false
          this.getList()
          this.formData = new FormData()
          if (flag) {
            this.$emit('update:currentTab', 'tab3')
          }
        })
        .catch(() => {
          this.formData = new FormData()
          this.submitLoading = false
        })
    },
    formatBeforeSave(data) {
      //依据实际需求处理
      let tmp = _.cloneDeep(data)
      tmp.label_id = this.laberDesignId
      if (tmp.detail_list.length > 0) {
        tmp.detail_list.forEach((i) => {
          i.value = i.value ? i.value.join(',') : ''
          i.allow_null_value = i.allow_null_value ? i.allow_null_value.join(',') : ''
        })
      }
      if (!tmp.file_list.length) {
        tmp['file_id'] = null
      } else {
        delete tmp['file_id']
      }
      delete tmp.labels
      delete tmp.file_list
      return tmp
    },
    typeChange(v) {
      if (v == 2) {
        this.data.size = ''
        this.data.content = '{}'
        this.labelUploaderProps = {
          limit: 1,
          action: '',
          'auto-upload': false,
          onSuccess: this.afterUpload,
          onRemove: this.onRemove,
          onPreview: this.onPreview,
          onExceed: this.onExceed,
          onChange: this.onChange,
          headers: { Authorization: 'Bearer ' + getToken() },
        }
      } else if (v == 3) {
        this.data.size = ''
        this.data.content = '{}'
        this.labelUploaderProps = {
          limit: 1,
          action: '',
          accept: '.btw',
          'auto-upload': false,
          onSuccess: this.afterUpload,
          onRemove: this.onRemove,
          onPreview: this.onPreview,
          onExceed: this.onExceed,
          onChange: this.onChange,
          headers: { Authorization: 'Bearer ' + getToken() },
        }
      } else {
        this.formData = new FormData()
      }
    },
    getTabInit() {
      this.$request(this.$api.factor + 'getlist', { page: 1, size: 10, coding_type: 'view' }).then((r) => {
        this.$request(this.$api.param + 'getlist', { page: 1, size: 10, paramType: 'LABEL_VIEW_FIELDS' }).then((r2) => {
          this.viewOptions = r.list.map((i) => ({
            label: `${i.coding_param} ${i.coding_desc}`,
            value: i.coding_param,
            children: r2.list.filter((j) => j.param_name == i.coding_param),
          }))
        })
      })
    },
    labelDesign(id) {
      this.designUrl = `${this.designBaseUrl}?id=${id}&api=${this.$api.label}`
      this.designVisible = true
    },
    getInfo() {
      this.pageLoading = true
      let url = this.apiSingle
      this.$request(url, {
        id: this.laberDesignId,
        type: 1,
      })
        .then((r) => {
          this.data = this.formatAfterGet(r)
          this.labelFiles = r.file_list
          this.typeChange(r.document_type)
        })
        .finally(() => {
          this.pageLoading = false
        })
    },

    formatAfterGet(data) {
      //依据实际需求处理
      data.labels = data.file_list.length ? [{ name: data.file_list[0].name, url: data.file_list[0].url }] : []
      data.label_type = data.label_type.toString()
      let detailArray = data.detail_list
      detailArray.forEach((i) => {
        i.value = i.value ? i.value.split(',') : []
        i.allow_null_value = i.allow_null_value ? i.allow_null_value.split(',') : []
      })
      return data
    },
    addDetail(i) {
      i = i || 0
      this.data.detail_list.splice(i + 1, 0, {})
    },
    fieldOptions(v) {
      let t = this.viewOptions.find((i) => i.value == v.name)
      return t ? t.children : []
    },
    removeDetail(i) {
      this.data.detail_list.splice(i, 1)
    },
    afterUpload(r, f, l) {
      // this.$message({
      //   message: '上传成功',
      //   type: 'success',
      // })
      // this.data.name = f.name
      // this.data.file_path = r
    },
    onRemove(file, fileList) {
      this.formData = new FormData()
      this.data.file_list = []
      this.labelFiles = []
    },
    onPreview(f) {
      download(this.$api.baseUrl, f)
    },
    onExceed(files, fileList) {
      this.$message({
        message: '只允许上传一个文件，如许更改，请先删除已上传的文件。',
        type: 'error',
      })
    },
    // 上传
    onChange(file, fileList) {
      if (this.labelUploaderProps.accept) {
        if (!file.name.includes(this.labelUploaderProps.accept)) {
          this.$message.error('文件类型错误,请上传指定文件')
          fileList.splice(0, 1)
          return false
        }
      }
      this.data.name = file.name
      this.formData.append('files', file.raw)
    },
  },
}
</script>

<style lang="scss">
</style>